#include "bsp_timer.h"

gptimer_handle_t gptimer1 = NULL;
gptimer_handle_t gptimer2 = NULL;
gptimer_config_t timer_config = {
    .clk_src = GPTIMER_CLK_SRC_DEFAULT,
    .direction = GPTIMER_COUNT_UP,
    .resolution_hz = 1000000, // 1MHz, 1 tick=1us

};

gptimer_config_t timer_config2 = {
    .clk_src = GPTIMER_CLK_SRC_DEFAULT,
    .direction = GPTIMER_COUNT_UP,
    .resolution_hz = 1000000, 
};

gptimer_alarm_config_t alarm_config = {
    .reload_count = 0, // counter will reload with 0 on alarm event
    .alarm_count = 500000, // period = 1s @resolution 1MHz
    .flags.auto_reload_on_alarm = true, // enable auto-reload
};

gptimer_alarm_config_t alarm_config2 = {
    .reload_count = 0, 
    .alarm_count = TIMER2_BASE_TICK, 
    .flags.auto_reload_on_alarm = true, // enable auto-reload
};

void mygptimer_init(gptimer_alarm_cb_t callback_func)
{
    gptimer_event_callbacks_t cbs = {
        .on_alarm = callback_func, // register user callback
    };
    ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &gptimer1));
    ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer1, &cbs, NULL));
    ESP_ERROR_CHECK(gptimer_enable(gptimer1));
    ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer1, &alarm_config));

    ESP_ERROR_CHECK(gptimer_start(gptimer1));

}

void mygptimer2_init(gptimer_alarm_cb_t callback_func)
{
    gptimer_event_callbacks_t cbs = {
        .on_alarm = callback_func, // register user callback
    };
    ESP_ERROR_CHECK(gptimer_new_timer(&timer_config2, &gptimer2));
    ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer2, &cbs, NULL));
    ESP_ERROR_CHECK(gptimer_enable(gptimer2));
    ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer2, &alarm_config2));

    // ESP_ERROR_CHECK(gptimer_start(gptimer2));

}

void gptimer1_close()
{
    gptimer_stop(gptimer1);
}
void gptimer1_open()
{
    gptimer_start(gptimer1);
}


void gptimer2_close()
{
    gptimer_stop(gptimer2);
}
void gptimer2_open()
{
    gptimer_start(gptimer2);
}



